<template>
	<view class="attraction-detail-page">
		<!-- 1. 自定义导航栏 -->
		<view class="custom-navbar" :class="{ 'is-sticky': isNavbarSticky }" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="nav-content">
				<u-icon name="arrow-left" :color="isNavbarSticky ? '#000' : '#000'" size="22" @click="goBack" bold></u-icon>
				<!-- 粘性状态下显示标题 -->
				<text v-if="isNavbarSticky" class="nav-title">{{ attractionInfo.name }}</text>
				<u-icon name="share-square" :color="isNavbarSticky ? '#000' : '#000'" size="22" @click="share" bold></u-icon>
			</view>
		</view>

		<!-- 吸顶状态下固定的筛选栏 -->
		<view class="sticky-tabs-fixed-container" v-if="isTabsSticky" :style="{ top: statusBarHeight+navBarHeight + 'px' }">
			<view class="filter-tabs-container">
				<view class="filter-tabs">
					<view
						v-for="(tab, index) in subTabList"
						:key="index"
						:class="['tab-item', { 'active': currentSubTab === index }]"
						:style="currentSubTab === index ? { backgroundColor: tab.activeColor, color: tab.activeTextColor, borderColor: tab.activeColor } : {}"
						@click="handleTabChange(index)"
					>
						<text class="tab-name">{{ tab.name }}</text>
						<text class="count">{{ tab.count }}</text>
					</view>
				</view>
				<view class="dropdown-icon" @click="showFilterPopup = true">
					<u-icon name="arrow-down" color="#666" size="14"></u-icon>
				</view>
			</view>
		</view>

		<!-- 2. 主滚动区域 -->
		<scroll-view scroll-y class="main-scroll-view" @scroll="handleScroll" @scrolltolower="loadMorePosts">
			<!-- 顶部背景图 -->
			<view class="header-background">
				<u-image width="100%" :src="attractionInfo.image" mode="widthFix"></u-image>
			</view>

			<!-- 景点介绍 -->
			<view class="attraction-info-card">
				<view class="info-header">
					<view class="info-left">
						<view class="info-left-title">
							<text class="title">{{ attractionInfo.name }}</text>
							<text class="subtitle">{{ attractionInfo.category }}</text>
						</view>
						<view class="rating-bar">
							<text class="rate">避坑指数</text>
							<CustomRating :rating="attractionInfo.rating" />
							<text class="score">{{ attractionInfo.rating.toFixed(1) }}</text>
							<text class="reviews">{{ attractionInfo.reviews }}条</text>
						</view>
						<text class="address">xx省xx市{{ attractionInfo.district }}{{ attractionInfo.address }}xx道xx号</text>
					</view>
					<view class="info-right" @click="openMap">
						<view class="navigation-button">
							<!-- <u-icon name="map-fill" color="#f0f0f0" size="20"></u-icon> -->
							<text class="indexIconFont icon-dw"></text>
							<text>导航</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- ③ 筛选Tab栏 (作为吸顶触发锚点) -->
			<view id="tabs-trigger-anchor" class="filter-tabs-container">
				<view class="filter-tabs">
					<view
						v-for="(tab, index) in subTabList"
						:key="index"
						:class="['tab-item', { 'active': currentSubTab === index }]"
						:style="currentSubTab === index ? { backgroundColor: tab.activeColor, color: tab.activeTextColor, borderColor: tab.activeColor  } : {}"
						@click="handleTabChange(index)"
					>
						<text class="tab-name">{{ tab.name }}</text>
						<text class="count">{{ tab.count }}</text>
					</view>
				</view>
				<view class="dropdown-icon" @click="showFilterPopup = true">
					<u-icon name="arrow-down" color="#000" size="14"></u-icon>
				</view>
			</view>
			
			<!-- 筛选条件弹出层 -->
			<u-popup :show="showFilterPopup" @close="showFilterPopup = false" mode="top" :overlay-style="{top: navBarHeight + 'px'}" round="0">
				<view class="filter-popup-content-new" :style="{ paddingTop: navBarHeight + 'px' }">
			        <view class="popup-header">
			            <text class="popup-title">选择避坑分类</text>
			            <u-icon name="close" size="18" color="#000" bold @click="showFilterPopup = false"></u-icon>
			        </view>
			        <scroll-view scroll-y class="popup-scroll-view">
			            <view class="popup-list">
			                <view
			                    v-for="(tab, index) in subTabList"
			                    :key="index"
			                    class="popup-list-item"
			                    :style="getGradientStyle(tab)"
			                    @click="handleTabChange(index, true)"
			                >
			                    <text class="item-name">{{ tab.name }}</text>
			                    <view class="item-right">
			                        <text class="item-count">{{ tab.count }}</text>
			                        <u-icon v-if="currentSubTab === index" name="checkmark" color="#F66B2F" size="20"></u-icon>
			                        <view v-else class="checkmark-placeholder"></view> <!-- Placeholder to maintain alignment -->
			                    </view>
			                </view>
			            </view>
			        </scroll-view>
			    </view>
			</u-popup>

			<!-- ④ 瀑布流 -->
			<view class="waterfall-section">
				<WaterfallPosts 
					:left-list="leftList" 
					:right-list="rightList"
					@itemClick="navigateToPostDetail"
				/>
				<u-loadmore :status="loadStatus" />
			</view>

		</scroll-view>

		<!-- ⑤ 底部聊避坑按钮 -->
		<view class="floating-action-button" @click="navigateToPitfallRelease">
			<image class="button-icon" src="/static/index/featured/icon_cyht.png" mode="widthFix"></image>
			<text class="floating-button-text">聊避坑</text>
		</view>

	</view>
</template>

<script>
import WaterfallPosts from '@/components/index/waterfall-posts/waterfall-posts.vue';
import CustomRating from '@/components/CustomRating/CustomRating.vue';
import { getPosts } from '@/request/api.js';
import config from '@/config/index.js';

export default {
	components: { WaterfallPosts, CustomRating },
	data() {
		return {
			// --- 导航与布局 ---
			statusBarHeight: 0,
			navBarHeight: 0,
			isNavbarSticky: false,
			isTabsSticky: false, 
			stickyTriggerTop: 0, 

			// --- 页面数据 ---
			attractionInfo: { rating: 0 },

			// --- Tab筛选 ---
			subTabList: [
				{ name: '综合', count: 7134, categoryId: 0, activeColor: '#000000', activeTextColor: '#fff' },
				{ name: '停车难', count: 3514, categoryId: 1, activeColor: '#FF452C', activeTextColor: '#fff' },
				{ name: '旺季劝退', count: 2611, categoryId: 2, activeColor: '#F66B2F', activeTextColor: '#fff' },
				{ name: '物价高', count: 651, categoryId: 3, activeColor: '#FFB427', activeTextColor: '#fff' },
				{ name: '商业化过度', count: 358, categoryId: 4, activeColor: '#3A9DFA', activeTextColor: '#fff' }
			],
			currentSubTab: 0,
			showFilterPopup: false,

			// --- 瀑布流 ---
			leftList: [],
			rightList: [],
			page: 1,
			pageSize: 10,
			isLoading: false,
			loadStatus: 'loadmore',
		};
	},
	onLoad(options) {
		const systemInfo = uni.getSystemInfoSync();
		this.statusBarHeight = systemInfo.statusBarHeight;
		this.navBarHeight = this.$store.state.systemInfo.navBarHeight;

		if (options.item) {
			this.attractionInfo = JSON.parse(decodeURIComponent(options.item));
			this.attractionInfo.rating = Number(this.attractionInfo.rating) || 0;
		} else {
			this.attractionInfo = { id: 0, name: '景点详情', image: '', rating: 4.0, reviews: 0, category: '未知', district: '', address: '地址未知' };
			uni.showToast({ title: '加载景点信息失败', icon: 'none' });
		}
		
		this.loadPosts(true);
	},
	onReady() {
		this.$nextTick(this.calculateStickyPosition);
	},
	computed: {
	    maxCount() {
	        if (!this.subTabList || this.subTabList.length === 0) {
	            return 1; // Avoid division by zero
	        }
	        // Find the highest count among all categories
	        return Math.max(...this.subTabList.map(item => item.count));
	    }
	},
	methods: {
		// --- 页面交互 ---
		goBack() { uni.navigateBack(); },
		share() { uni.showToast({ title: '分享功能待实现', icon: 'none' }); },
	
		handleScroll(e) {
			const scrollTop = e.detail.scrollTop;
			this.isNavbarSticky = scrollTop > 50;
			if (this.stickyTriggerTop > 0) {
				this.isTabsSticky = scrollTop >= this.stickyTriggerTop;
			}
		},

		calculateStickyPosition() {
			const query = uni.createSelectorQuery().in(this);
			query.select('#tabs-trigger-anchor').boundingClientRect(data => {
				if (data) {
					this.stickyTriggerTop = data.top - this.navBarHeight;
				}
			}).exec();
		},
		
		getGradientStyle(item) {
			const ratio = item.count / this.maxCount;
	
			// Define start (cool) and end (hot) colors in RGB
			const coolColor = [232, 245, 253]; // Light Blue
			const hotColor = [255, 232, 232];  // Light Pink/Red
	
			// Interpolate RGB values based on the ratio
			const r = Math.round(coolColor[0] + ratio * (hotColor[0] - coolColor[0]));
			const g = Math.round(coolColor[1] + ratio * (hotColor[1] - coolColor[1]));
			const b = Math.round(coolColor[2] + ratio * (hotColor[2] - coolColor[2]));
			
			// The alpha (transparency) also increases with the count for more intensity
			const alpha = 0.4 + ratio * 0.5; // From 0.4 to 0.9 opacity
			
			// The gradient will cover more of the item as the count increases
			const stopPosition = 60 + ratio * 40; // Stops between 60% and 100%
	
			return {
				background: `linear-gradient(to right, rgba(${r}, ${g}, ${b}, ${alpha}), white ${stopPosition}%)`
			};
		},
		
		handleTabChange(index, fromPopup = false) {
			if (this.currentSubTab === index) {
				if(fromPopup) this.showFilterPopup = false;
				return;
			}
			this.currentSubTab = index;
			if(fromPopup) this.showFilterPopup = false;
			this.loadPosts(true);
		},

		// --- 数据加载 ---
		async loadPosts(isRefresh = false) {
			if (this.isLoading || (!isRefresh && this.loadStatus === 'nomore')) return;

			this.isLoading = true;
			if (isRefresh) {
				this.page = 1; this.leftList = []; this.rightList = [];
			}
			this.loadStatus = 'loading';

			const params = {
				userId: this.$store.state.userInfo.userId,
				queryType: 3,
				// categoryId: this.subTabList[this.currentSubTab].categoryId,
				pageNum: this.page,
				pageSize: this.pageSize
			};

			try {
				const res = await getPosts(params);
				if (res.data && res.data.code === 200) {
					const formattedPosts = (res.data.rows || []).map(this.formatApiData);
					this.distributePostsToColumns(formattedPosts);
					
					if (formattedPosts.length < this.pageSize) {
						this.loadStatus = 'nomore';
					} else {
						this.page++; this.loadStatus = 'loadmore';
					}
				} else { this.loadStatus = 'loadmore'; }
			} catch (error) { this.loadStatus = 'loadmore'; } 
			finally { this.isLoading = false; }
		},
		loadMorePosts() { this.loadPosts(false); },

		// --- 数据处理 ---
		formatApiData(item) {
			const coverImage = (item.files && item.files.length > 0 && item.files[0].fileUrl) ? (item.files[0].fileUrl.startsWith('http') ? item.files[0].fileUrl : config.cdnURL + item.files[0].fileUrl) : '';
			const authorAvatar = item.avatar ? (item.avatar.startsWith('http') ? item.avatar : config.cdnURL + item.avatar) : '/static/demo/avatar_default.png';
			return { id: item.id, image: coverImage, content: item.content, author: { avatar: authorAvatar, name: item.nickName || '匿名用户' }, isLiked: item.isLiked, likeCount: item.likeCount, ...item };
		},
		distributePostsToColumns(newPosts) {
			newPosts.forEach(post => {
				(this.leftList.length <= this.rightList.length ? this.leftList : this.rightList).push(post);
			});
		},
		
		// --- 页面跳转 ---
		navigateToPostDetail(item) {
			uni.navigateTo({
				url: `/pages_sub/index/rich-post-detail/rich-post-detail`,
				success: (res) => res.eventChannel.emit('acceptDataFromOpenerPage', { item: item })
			});
		},
		navigateToPitfallRelease() {
			uni.navigateTo({ url: `/pages_sub/release/release/release?from=pitfall` });
		},
		openMap() {
			uni.showToast({ title: '导航功能待开发', icon: 'none' });
		}
	}
};
</script>

<style lang="scss" scoped>
.attraction-detail-page {
	background-color: #f8f8f8;
}

.custom-navbar {
	position: fixed; top: 0; left: 0; right: 0; z-index: 100;
	transition: background-color 0.3s;
	background-color: transparent;
	&.is-sticky {
		background-color: #fff;
		box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);
	}
	.nav-content {
		display: flex; align-items: center; justify-content: space-between;
		height: 44px; padding: 0 30rpx;
		.nav-title {
			font-size: 34rpx;
			font-weight: bold;
			color: #000;
		}
	}
}

.sticky-tabs-fixed-container {
	position: fixed;
	left: 0;
	right: 0;
	z-index: 99;
	background-color: #fff;
	.filter-tabs-container {
		border-bottom: 1rpx solid #f0f0f0;
	}
}

.main-scroll-view {
	height: 100vh;
}

.header-background {
	width: 100%;
}

.attraction-info-card {
	background-color: #fff;
	padding: 30rpx;
	// margin: -80rpx 0 0; // 左右无边距
	// border-radius: 20rpx 20rpx 0 0; // 只有顶部圆角
	position: relative;
	z-index: 2;
	border-bottom: 1rpx solid #f0f0f0;

	.info-header {
		display: flex; justify-content: space-between;align-items: flex-end;
		.info-left {
			.info-left-title{
				display: flex;
				align-items: self-end;
				margin-bottom: 10rpx;
				.title { display: block; font-size: 36rpx; font-weight: bold; margin-right: 20rpx; }
				.subtitle { display: block; font-size: 26rpx; color: #666;  }
			}
			
			.rating-bar {
				display: flex; align-items: center; font-size: 24rpx; color: #000; margin-bottom: 10rpx;line-height: 50rpx;
				.rate{
					margin-right: 10rpx;
				}
				.score { color: #F66B2F; margin: 0 20rpx; }
			}
			.address { font-size: 24rpx; color: #000; }
		}
		.info-right .navigation-button {
			display: flex; flex-direction: column; align-items: center;
			background-color: transparent; // 无背景色
			border-radius: 12rpx; padding: 10rpx 16rpx;
			.icon-dw{
				color: #f81217;
				font-size: 30rpx;
			}
			text { font-size: 22rpx; margin-top: 4rpx; color: #666; }
		}
	}
}

.filter-tabs-container {
	display: flex;
	align-items: center;
	padding: 20rpx 30rpx;
	background-color: #fff;
	.filter-tabs {
		flex: 1; display: flex; align-items: center;
		overflow-x: auto;
		-webkit-overflow-scrolling: touch;
		&::-webkit-scrollbar { display: none; }
		
		.tab-item {
			display: flex;
			flex-direction: column; // 上下布局
			align-items: center; // 居中
			justify-content: center;
			padding: 10rpx 18rpx; margin-right: 20rpx; border-radius: 20rpx; // 调整为小圆角
			background-color: #ffffff; color: #000;
			border: 2rpx solid #B1AFAD;
			transition: all 0.2s;
			white-space: nowrap;
			
			&.active { font-weight: bold; }
			.tab-name { font-size: 28rpx; line-height: 30rpx; }
			.count { font-size: 22rpx; margin-top: 2rpx; opacity: 1; line-height: 22rpx; }
		}
	}
	.dropdown-icon { padding: 10rpx; }
}

.filter-popup-content-new {
	display: flex;
	flex-direction: column;
	max-height: 70vh; // Limit popup height
	padding: 30rpx 0;
	padding-bottom: calc(30rpx + env(safe-area-inset-bottom));

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		padding: 0 30rpx;
		.popup-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #303133;
		}
	}
	
	.popup-scroll-view {
		flex: 1;
	}

	.popup-list-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 20rpx;
		border-bottom: 1rpx solid #f5f5f5;
		transition: background-color 0.2s;

		&:last-child {
			border-bottom: none;
		}

		.item-name {
			font-size: 30rpx;
			color: #333;
		}
		
		.item-right {
			display: flex;
			align-items: center;
		}

		.item-count {
			font-size: 28rpx;
			color: #666;
			margin-right: 24rpx;
		}
		
		.checkmark-placeholder {
			width: 20px; // Same width as the checkmark icon
		}
	}
}

.waterfall-section { padding: 20rpx 0; background-color: #fff;}

.floating-action-button {
	position: fixed;
	bottom: 150rpx;
	left: 50%;
	transform: translateX(-50%);
	z-index: 99;
	display: flex;
	align-items: center;
	padding: 18rpx 36rpx;
	border-radius: 40rpx;
	background-color: #000;
	box-shadow: 0 8rpx 20rpx rgba(0,0,0,0.2);

	.button-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 12rpx;
	}

	.floating-button-text {
		font-size: 30rpx;
		font-weight: bold;
		/* 设置背景渐变 */
		background: linear-gradient(to bottom, #ffde06, #68ff0a);
		/* 限制背景只显示文字区域 */
		-webkit-background-clip: text;
		background-clip: text;
		/* 确保文字颜色透明，使背景色显示 */
		color: transparent;
		background-clip: text;
		color: transparent;
	}
}
</style>